﻿
using FullCoreDBModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Linq;

namespace FullCoreWebApi.Common
{
    public class ApiResultFilterAttribute : ActionFilterAttribute
    {
        private readonly ILogger<ApiResultFilterAttribute> _logger;
        public ApiResultFilterAttribute(ILogger<ApiResultFilterAttribute> logger)
        {
            _logger = logger;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);

            _logger.LogInformation("请求地址：" + context.HttpContext.Request.Path);
            _logger.LogInformation("请求方式：" + context.HttpContext.Request.Method);
            if (context.ActionArguments.Count > 0)
            {
                _logger.LogInformation("请求参数：" + JsonConvert.SerializeObject(context.ActionArguments.Select(a => a.Value)));
            }
        }

        public override void OnResultExecuting(ResultExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                if (context.Result is ObjectResult objectResult)
                {
                    context.Result = new ObjectResult(new ResponseApi<object> { code = 400, msg = "验证错误", data = objectResult.Value });
                }
            }
            else
            {
                if (context.Result is ObjectResult objectResult)
                {
                    context.Result = new ObjectResult(new ResponseApi<object> { code = 200, msg = "成功", data = objectResult.Value });
                }
                else if (context.Result is EmptyResult)
                {
                    context.Result = new ObjectResult(new ResponseApi<string> { code = 404, msg = "未找到资源" });
                }
                else if (context.Result is ContentResult contentResult)
                {
                    context.Result = new ObjectResult(new ResponseApi<object> { code = 200, msg = "成功", data = contentResult.Content });
                }
                else if (context.Result is StatusCodeResult statusResult)
                {
                    context.Result = new ObjectResult(new ResponseApi<string> { code = statusResult.StatusCode, data = "", msg = "" });
                }
            }
        }
    }
}
